<?php
class AdvertisersController extends AppController
{
    var $name = 'Advertisers';
    
    function beforeFilter()
    {
        $this->Security->disabledFields = array(
            'Attachment',
            'Advertiser.name',
            'Advertiser.id',
            'Advertiser.position',
            'Advertiser.type',
            'Advertiser.link',            
            'Advertiser.code',
            'Advertiser.view',
            'Advertiser.click',
            'Advertiser.max_view',
            'Advertiser.max_click',            
            'Advertiser.note',
            'Advertiser.status',
            'Advertiser.order',
            'Advertiser.created',
            'Advertiser.end_date',
        );
        parent::beforeFilter();
    }
    
    function view()
    {
        $position    = isset($this->params['named']['position'])? $this->params['named']['position'] : 1;
        
        $advertisers = $this->Advertiser->find('first',array(
                            'conditions' => array(
                                'position' => $position
                                ),
                                'fields'   => array(
                                    'type',
                                    'name',
                                    'code'
                                ),
                                'limit'    => '3',
                            ));
        return $advertisers;
    }
    
    function admin_index($city_slug = null)
    {
        $this->disableCache();
        $title = '';
        $this->_redirectGET2Named(array(
            'filter_id',
            'q'
        ));
        $conditions = array();
        if (!empty($this->params['named']['city_slug'])) {
            $city_id = $this->Advertiser->City->find('first', array(
                'conditions' => array(
                    'City.slug' => $this->params['named']['city_slug']
                ) ,
                'recursive' => -1
            ));
			$city_filter_id = $city_id['City']['id'];
        }
        if (!empty($this->data['Advertiser']['filter_id'])) {
            $this->params['named']['filter_id'] = $this->data['Advertiser']['filter_id'];
        }

        if (!empty($this->data['Advertiser']['q'])) {
            $this->params['named']['q'] = $this->data['Advertiser']['q'];
        }

        
        $this->pageTitle = sprintf(__l(' %s Advertisers') , $title);
        if (isset($this->params['named']['q'])) {
			$conditions['Advertiser.name LIKE'] = '%' . $this->params['named']['q'] . '%';
            $this->pageTitle.= sprintf(__l(' - Search - %s') , $this->params['named']['q']);
        }
        
        if (!empty($this->params['named']['q'])) {
            $this->paginate['search'] = $this->params['named']['q'];
        }
                
        // Citywise admin filter //
		if(!empty($city_filter_id)){
            $advertiser_cities = $this->Advertiser->CitiesAdvertiser->find('first', array(
                'conditions' => array(
                    'CitiesAdvertiser.city_id' => $city_filter_id
                ) ,
                'fields' => array(
                    'CitiesAdvertiser.advertiser_id'
                ),
                'recursive' => 1
            )); 
			foreach($advertiser_cities['CitiesAdvertiser'] as $advertiser_city){
				$city_advertiser_id[] = $advertiser_city['advertiser_id'];
			}
			if(!empty($city_advertiser_id)){
              //  $city_advertiser_id = implode(',',$city_advertiser_id);
				$conditions['Advertiser.id'] = $city_advertiser_id;
               // $conditions['Advertiser.id'] = 2;
			}
		}
        $this->paginate = array(
           'conditions' => $conditions,
            'contain' => array(
                'City' => array(
                    'fields' => array(
                        'City.id',
                        'City.name',
                        'City.slug',
                    )
                ) 
            ) ,
            'order' => array(
                'Advertiser.id' => 'desc'
            )
        );
        if (!empty($moreActions)) {
            $this->set(compact('moreActions'));
        }
        $advertisercount = $this->Advertiser->find('count',array('conditions'=>$conditions));
        
        $this->set('advertisercount',$advertisercount);
        $this->set('advertisers', $this->paginate());
        $this->set('pageTitle', $this->pageTitle);
    }
    
    function admin_add()
    {
        $this->pageTitle = __l('Add Advertiser');
		$this->loadModel('Attachment');
        $this->Advertiser->Behaviors->attach('ImageUpload', Configure::read('image.file'));
        
        if (!empty($this->data)) {
            //attachement del if has:
            if (!empty($this->data['OldAttachment'])) 
            {
                $attachmentIds = array();
                foreach($this->data['OldAttachment'] as $attachment_id => $is_checked) {
                   if (isset($is_checked['id']) && ($is_checked['id'] == 1)) {
                        $attachmentIds[] = $attachment_id;
                    }
                }
                $attachmentIds = array(
                    'Attachment' => $attachmentIds
                );

				if (!empty($attachmentIds)) {
                    $this->Advertiser->Attachment->del($attachmentIds);
                }
            }
            unset($this->data['OldAttachment']);
                       
            $this->Advertiser->set($this->data);			
			$this->Advertiser->City->set($this->data);
            
		    if ($this->Advertiser->validates() ) 
            {
                    $this->Advertiser->create();
                    $this->Advertiser->save($this->data);
					$foreign_id = $this->Advertiser->getLastInsertId();	
                                        
                    if (!empty($this->data['Attachment']['filename']['tmp_name'])) 
                    {
                        $image_info = getimagesize($this->data['Attachment']['filename']['tmp_name']);
                        $this->data['Attachment']['filename']['type'] = $image_info['mime'];
                        $this->data['Attachment']['foreign_id']  = $foreign_id;
                        $this->data['Attachment']['description'] = 'Advertiser';
                        $this->data['Attachment']['class'] = 'Advertiser';
                        $this->Advertiser->Attachment->Behaviors->attach('ImageUpload', Configure::read('photo.file'));
                        $this->Advertiser->Attachment->create();
                        $this->Advertiser->Attachment->save($this->data);                        
                    }
                    $this->Session->setFlash(__l('Advertiser has been added.') , 'default', null, 'success');
                    $this->redirect(array(
                        'controller' => 'advertisers',
                        'action' => 'index'
                    ));				
					
            } else 
            {
                $this->Session->setFlash(__l('Advertiser could not be added. Please, try again.') , 'default', null, 'error');
				
            }
        } else {
            if ($this->Auth->user('group_id') == ConstUserTypes::User) {
                $this->cakeError('error404');
            } elseif ($this->Auth->user('group_id') == ConstUserTypes::Company) {
               
            }
        }
       
        $cities = $this->Advertiser->City->find('list', array(
            'conditions' => array(
                'City.is_approved =' => 1
            ) ,
            'order' => array(
                'City.name' => 'asc'
            )
        ));
	
        $this->set(compact('cities'));		
    }
    function flashupload()
    {
        $this->Advertiser->Attachment->Behaviors->attach('ImageUpload', Configure::read('photo.file'));
        $this->XAjax->flashupload();
    }
    
    function admin_edit($id = null)
    {
        $this->pageTitle = __l('Edit Advertiser');
        if (is_null($id)) {
            $this->cakeError('error404');
        }
        $id = !empty($id) ? $id : $this->data['Advertiser']['id'];
        $advertiser = $this->Advertiser->find('first', array(
                        'conditions' => array(
                            'Advertiser.id' => $id
                        ) ,
                        'contain' => array(
                            'City'
                        ) ,
                        'recursive' => 1
                    ));
                    
        if (empty($advertiser)) {
            $this->cakeError('error404');
        }
        if (!empty($this->data)) {
            //del image 
            if (!empty($this->data['OldAttachment'])) {
                $attachmentIds = array();
                foreach($this->data['OldAttachment'] as $attachment_id => $is_checked) {
                    if (isset($is_checked['id']) && ($is_checked['id'] == 1)) {
                        $attachmentIds[] = $attachment_id;
                    }
                }
                $attachmentIds = array(
                    'Attachment' => $attachmentIds
                );
                if (!empty($attachmentIds)) {
                    $this->Advertiser->Attachment->del($attachmentIds);
                }
            }
            unset($this->data['OldAttachment']);
            
            //set city:
            $this->Advertiser->City->set($this->data);
            
            if ($this->Advertiser->validates())
            {
                if ($this->Advertiser->save($this->data)) {
                    
                    $this->Advertiser->set($this->data);
                    $foreign_id = $this->Advertiser->id;
                    $is_form_valid= true;
                    
                    if (!empty($this->data['Attachment']['filename']['tmp_name'])) 
                    {
                        $image_info = getimagesize($this->data['Attachment']['filename']['tmp_name']);
                        $this->data['Attachment']['filename']['type'] = $image_info['mime'];
                        $this->data['Attachment']['foreign_id']  = $foreign_id;
                        $this->data['Attachment']['description'] = 'Advertiser';
                        $this->data['Attachment']['class'] = 'Advertiser';
                        $this->Advertiser->Attachment->Behaviors->attach('ImageUpload', Configure::read('photo.file'));
                        $this->Advertiser->Attachment->create();
                        $this->Advertiser->Attachment->save($this->data);
                        if (!$this->Advertiser->validates() |!$this->Advertiser->Attachment->validates()) {
                            $attachmentValidationError[$i] = $this->Advertiser->Attachment->validationErrors;
                            $is_form_valid = false;
                            $this->Session->setFlash(__l('Advertiser could not be updated. Please, try again.') , 'default', null, 'error');
                        }
                    }
                    if ($is_form_valid) {
                        $this->Session->setFlash(__l('Advertiser has been updated.') , 'default', null, 'success');
                    }
                    $this->redirect(array(
                        'controller' => 'advertisers',
                        'action' => 'index'
                    ));
                }
            } else {
                $this->Session->setFlash(__l('Advertiser could not be updated. Please, try again.') , 'default', null, 'error');
            }
        }else
        {
            $this->data = $this->Advertiser->find('first', array(
                'conditions' => array(
                    'Advertiser.id' => $id
                ) ,
                'recursive' => 1
            ));
            
            if (!empty($this->data['Advertiser']['end_date'])) {
                if(strtotime($this->data['Advertiser']['end_date'])<strtotime($this->data['Advertiser']['created']))
                {
                    $this->data['Advertiser']['end_date']   = '';
                }else
                {
                    $this->data['Advertiser']['end_date'] = _formatDate('Y-m-d H:i:s', strtotime($this->data['Advertiser']['end_date']));
                }                
            }
            
        }
        $cities = $this->Advertiser->City->find('list', array(
            'conditions' => array(
                'City.is_approved =' => 1
            ) ,
            'order' => array(
                'City.name' => 'asc'
            )
        ));
	
        $this->set(compact('cities'));
    }
    
    function admin_delete($id = null)
    {
        if (is_null($id)) {
            $this->cakeError('error404');
        }
        if ($this->Advertiser->del($id)) {
            $this->Session->setFlash(__l('Advertiser deleted') , 'default', null, 'success');
            $this->redirect(array(
                'action' => 'index'
            ));
        } else {
            $this->Session->setFlash(__l('Advertiser not found') , 'default', null, 'error');
            $this->redirect(array(
                'action' => 'index'
            ));
        }
    }
}
?>